package dnl.toolbox.files;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.commons.io.IOUtils;

/**
 * 
 * @author Daniel Orr
 * 
 */
public class CopyUtils {

	/**
	 * Copies the given system resource to the given target location.
	 * 
	 * @param resourceName
	 *            resource's name. This name is used when calling
	 *            <code>ClassLoader.getSystemResource</code>.
	 * @param targetFile
	 *            full path of the target <b>file</b>.
	 * @return <code>true</code> if all went well.
	 */
	public static boolean copySystemResource(String resourceName, String targetFile) {
		return copySystemResource(resourceName, targetFile, false);
	}

	/**
	 * Copies the given system resource to the given target location.
	 * 
	 * @param resourceName
	 *            resource's name. This name is used when calling
	 *            <code>ClassLoader.getSystemResource</code>.
	 * @param targetFile
	 *            full path of the target <b>file</b>.
	 * @param setExecutable
	 *            if <code>true</code>, the file will be set as an executable
	 *            file.
	 * @return <code>true</code> if all went well.
	 */
	public static boolean copySystemResource(String resourceName, String targetFile,
			boolean setExecutable) {
		URL url = ClassLoader.getSystemResource(resourceName);
		File f = new File(targetFile);
		FileWriter w;
		try {
			w = new FileWriter(f);
			IOUtils.copy(new InputStreamReader(url.openStream()), w);
			IOUtils.closeQuietly(w);
			if (setExecutable) {
				f.setExecutable(true);
				if (!f.canExecute()) {
					return false;
				}
			}
			if (!f.exists()) {
				return false;
			}
			return true;
		} catch (IOException e) {
			return false;
		}
	}
}
